
import Konva from 'konva'

/**
 *
 * @param {Konva.Stage} stage
 */
export const showFn = (stage) => {
  const imgs = stage.find('.img')
  const task = []
  imgs.forEach(img => {
    task.push(new Promise((resolve, reject) => {
      const image = new Image()
      image.src = img.attrs.url
      image.onload = () => {
        img.image(image)
        resolve()
      }
    }))
  })
  // stage.batchDraw()
  return Promise.allSettled(task)
}

/**
 * @param { { stage: import('konva').default.Stage, count: number} } param1
 * @param { Function } onReady
 */
export const useReady = ({ stage, count }, onReady = () => {}) => {
  const t1 = Date.now()
  const fa = (time) => {
    if (Date.now() - t1 > 3000) {
      Error('超时')
      return
    }
    if (stage) {
      const c = stage.find('.img').length
      console.log('c', c, count)
      if (c < count) {
        requestAnimationFrame(fa)
      } else {
        onReady()
      }
    } else {
      requestAnimationFrame(fa)
    }
  }
  requestAnimationFrame(fa)
}

/**
 * @param { import('konva').default.Stage } stage
 * @param { any } data
 */
export const useColor = (stage, data) => {
  // 0  未执行，1 完成，2执行中，3故障
  const colorMap = {
    0: [173, 178, 182],
    1: [88, 220, 151],
    2: [41, 238, 255],
    3: [250, 81, 81]
  }
  const layer = stage.findOne('Layer')
  const arrow = stage.find('Arrow')
  // console.log('data:', data, arrow)
  // 寻找到所有的label标签并清除掉
  stage.find('.label1').forEach(i => i.destroy())
  data.sceneParentNodeManagerList?.forEach(i => {
    let parentType = 2
    const flag = []
    i.sceneChildNodeManagerList?.forEach(j => {
      const status = j.executeStatus
      flag.push(String(status))
      const id = '#' + j.nodeId
      const node2 = stage.findOne(id)
      if (!node2) return
      /** @type {import('konva').default.Image} */
      const img = node2?.findOne('.img')
      if (img) {
        img.cache()
        img.filters([Konva.Filters.RGB])
        img.red(colorMap[status][0])
        img.green(colorMap[status][1])
        img.blue(colorMap[status][2])
        if (status == 2) {
          img.clearCache()
        }
        const { x, y } = img.getAbsolutePosition(stage)

        const label = createLabel({ x, y }, status)
        layer.add(label)
      }
      arrowColor(arrow, node2, status)
    })
    // 0  未执行，1 已完成，2执行中
    if (flag.every(i => i == 1 || i == 3)) {
      parentType = 1
    } else if (flag.every(i => i == 0)) {
      parentType = 0
    }

    const id = '#' + i.nodeId
    const node1 = stage.findOne(id)
    if (!node1) return
    /** @type {import('konva').default.Image} */
    const img = node1.findOne('.img')
    if (img) {
      img.cache()
      img.filters([Konva.Filters.RGB])
      img.red(colorMap[parentType][0])
      img.green(colorMap[parentType][1])
      img.blue(colorMap[parentType][2])
      if (parentType == 2) {
        img.clearCache()
      }
      const { x, y } = img.getAbsolutePosition(stage)

      const label = createLabel1({ x, y }, parentType)
      layer.add(label)
    }
    /** @type {Konva.Rect} */
    const rc = node1.findOne('Rect')
    if (rc) {
      if (parentType == 1) {
        rc.setAttr('stroke', '#58dc97')
      } else if (parentType == 0) {
        rc.setAttrs({
          stroke: '#76797c',
          fill: '#2f3a45'
        })
      }
    }
    arrowColor(arrow, node1, parentType)
  })
}
/**
 * @param { {x:number,y:number} } param0
 * @param {0|1|2|3} status
 * @returns {Konva.Group}
 */
const createLabel = ({ x, y }, status) => {
  const g = new Konva.Group({
    name: 'label1',
    x,
    y: y - 18 - 4
  })
  if (status == 0) {
    // const txtWidth = new Konva.Text({ text: '未开始', fontSize: 12 }).getClientRect().width
    const txt = new Konva.Text({
      text: '未开始',
      fill: '#abb0b4',
      fontSize: 12,
      fontFamily: 'Calibri',
      height: 18,
      align: 'center',
      verticalAlign: 'middle'
    })
    g.add(txt)
  }
  if (status == 1) {
    const txt = new Konva.Text({
      x: 6,
      text: '完成',
      fill: '#58dc97',
      fontSize: 12,
      fontFamily: 'Calibri',
      height: 18,
      align: 'center',
      verticalAlign: 'middle'
    })
    g.add(txt)
  }
  if (status == 2) {
    const rc = new Konva.Rect({
      y: -1,
      width: 45,
      height: 18,
      fill: '#29eeff'
    })
    g.add(rc)
    const txt = new Konva.Text({
      text: '执行中',
      fill: '#182531',
      fontSize: 12,
      fontFamily: 'Calibri',
      width: 45,
      height: 18,
      align: 'center',
      verticalAlign: 'middle'

    })
    g.add(txt)
    g.offsetX(4)
  }
  if (status == 3) {
    const rc = new Konva.Rect({
      y: -1,
      width: 30,
      height: 18,
      fill: '#fa5151'
    })
    g.add(rc)
    const txt = new Konva.Text({
      text: '故障',
      fill: '#fff',
      fontSize: 12,
      fontFamily: 'Calibri',
      width: 30,
      height: 18,
      align: 'center',
      verticalAlign: 'middle'

    })
    g.add(txt)
    g.offsetX(-3)
  }

  return g
}

/**
 * @param { {x:number,y:number} } param0
 * @param {0|1|2} status
 * @returns {Konva.Group}
 */
const createLabel1 = ({ x, y }, status) => {
  const g = new Konva.Group({
    name: 'label1',
    x,
    y: y - 18 - 4
  })

  const rc = new Konva.Rect({
    y: -1,
    width: 50,
    height: 18,
    fill: ''
  })
  g.add(rc)
  const txt = new Konva.Text({
    text: '',
    fill: '#182531',
    fontSize: 12,
    fontFamily: 'Calibri',
    width: 50,
    height: 18,
    align: 'center',
    verticalAlign: 'middle'

  })
  g.add(txt)

  if (status == 0) {
    rc.setAttr('fill', '#adb2b6')
    txt.setAttr('text', '未开始')
  }
  if (status == 1) {
    rc.setAttr('fill', '#58dc97')
    txt.setAttr('text', '已完成')
  }
  if (status == 2) {
    rc.setAttr('fill', '#29eeff')
    txt.setAttr('text', '执行中')
  }

  return g
}
/**
 *
 * @param {Konva.Arrow[]} arrows
 * @param {Konva.Group} node
 * @param {0|1|2} status
 */
const arrowColor = (arrows, node, status) => {
  const stage = node.getStage()
  const { x, y } = node.getAbsolutePosition(stage)
  const { width, height } = node.getClientRect()
  /** @type { Konva.Arrow} */
  let ar = null
  arrows.some(a => {
    const xy = a.getAbsolutePosition(stage)
    const [x1, y1] = a.points().slice(-2)
    if (x - 15 < xy.x + x1 && xy.x + x1 < x + width + 15 && y - 20 < xy.y + y1 && xy.y + y1 < y + height + 20) {
      ar = a
      return true
    }
  })
  const color = {
    0: '#76797c',
    1: '#58dc97',
    2: '#29eeff'
  }
  if (ar) {
    ar.setAttrs({
      stroke: color[status] || '#29eeff',
      fill: color[status] || '#29eeff'
    })
  }
}

/**
 * @param { import('konva').default.Stage } stage
 * @param { any } data
 * @param { Object } ref
 */
export const addEvt = (stage, data, ref) => {
  console.log('45')

  const arr = []
  data.sceneParentNodeManagerList?.forEach(e => {
    e.sceneChildNodeManagerList?.forEach(i => arr.push(i))
  })

  /** @type { Konva.Group[] } */
  const node2 = stage.find('.node2')
  node2.forEach(n => {
    n.on('click', (e) => {
      const { offsetX, offsetY } = e.evt
      const id = n.id()
      const node = arr.find(e => e.nodeId === id)
      console.log('arr', arr, id)
      ref.onActive({ offsetX, offsetY, node })
      stage.on('dragmove.clearActive', () => {
        ref.onActive(null)
        stage.off('dragmove.clearActive')
      })
    })
  })
}

/**
 * 给激活的节点添加激活边框
 * @param { import('konva').default.Stage } stage
 * @param { string } id
 */
export const activeRectFn = (stage, id) => {
  const layer = stage.findOne('#layer')
  layer.find('.activeRect').forEach(r => r.destroy())
  if (!id) return
  const nodeId = '#' + id
  const node2 = stage.findOne(nodeId)
  if (!node2) return
  const img = node2.findOne('.img')
  const { x, y } = img.getAbsolutePosition(stage)
  const rect = new Konva.Rect({
    name: 'activeRect',
    x: x - 1,
    y: y - 1,
    width: img.width() + 2,
    height: img.height() + 2,
    fill: 'transparent',
    stroke: '#ff00d1',
    strokeWidth: 1
  })
  layer.add(rect)
}
